package cn.edu.zafu.bigdata.x.xiejunjie.networkprogramming;

import java.io.*;
import java.net.*;

public class SimpleTCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080); // 监听8080端口
        System.out.println("等待客户端连接...");

        while (true) {
            Socket socket = serverSocket.accept(); // 接受客户端连接
            new Thread(new ClientHandler(socket)).start();
        }
    }

    static class ClientHandler implements Runnable {
        private final Socket socket;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) { // 读取消息
                    System.out.println("收到: " + inputLine);
                    out.println("回复: " + inputLine); // 回复相同的内容
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


